package cz.muni.fi.heathrow.daoImpl2;

import cz.muni.fi.heathrow.dao.DestinationDAO;
import cz.muni.fi.heathrow.entities.Destination;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Jan Richter
 */
@Repository
public class DestinationDAOImpl implements DestinationDAO
{

    @PersistenceContext
    private EntityManager manager;

    public DestinationDAOImpl()
    {
    }

    @Override
    public void createDestination(Destination destination)
    {
        if (destination == null)
            throw new IllegalArgumentException("Destination is null");
        if (destination.getId() != null)
            throw new IllegalArgumentException("Destination id is already set");

        manager.persist(destination);
    }

    @Override
    public Destination getDestination(Long id)
    {
        if (id == null)
            throw new IllegalArgumentException("Id is null");

        return manager.find(Destination.class, id);
    }

    @Override
    public void updateDestination(Destination destination)
    {
        if (destination == null)
            throw new IllegalArgumentException("Destination is null");
        if (destination.getId() == null)
            throw new IllegalArgumentException("Destination id is not set");

        manager.merge(destination);
    }

    @Override
    public void deleteDestination(Destination destination)
    {
        if (destination == null)
            throw new IllegalArgumentException("Destination is null");
        if (destination.getId() == null)
            throw new IllegalArgumentException("Destination id is not set");

        manager.remove(destination);
    }

    @Override
    public List<Destination> findAll()
    {
        TypedQuery<Destination> q = manager.createQuery("FROM Destination", Destination.class);
        return q.getResultList();
    }

    @Override
    public List<Destination> findDestinationWild(String text, int limit)
    {
        if (text == null)
            throw new IllegalArgumentException("text is null");

        TypedQuery<Destination> q = manager.createQuery("SELECT d FROM Destination AS d "
                + "WHERE d.city LIKE :text OR d.code LIKE :text", Destination.class);
        q.setParameter("text", "%" + text + "%");        
        q.setMaxResults(limit);
        return q.getResultList();
    }
}
